package com.wifeacountbook;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.wifeacountbook.provider.AcountKeeper;
import com.wifeacountbook.provider.AcountKeeper.ConsumeDetail;
import com.wifeacountbook.util.AcountKeeper.IncomeDetail;

public class AcountRecorder extends Activity implements OnClickListener {
	public static final String ACTION_CONSUME_RECORD_VIEW = "consume.record.view";
	public static final String ACTION_CONSUME_RECORD_ADD = "consume.record.add";
	public static final String ACTION_INCOME_RECORD_VIEW = "income.record.view";
	public static final String ACTION_INCOME_RECORD_ADD = "income.record.add";

	private static final int CONSUME_TYPE_DIALOG_ID = 0;
	private static final int PAY_ACOUNT_DIALOG_ID = 1;
	private static final int PAY_TIME_DIALOG_ID = 2;

	private static final int ACTIVITY_STATUS_CONSUME_ADD = 3;
	private static final int ACTIVITY_STATUS_CONSUME_VIEW = 4;
	private static final int ACTIVITY_STATUS_INCOME_ADD = 5;
	private static final int ACTIVITY_STATUS_INCOME_VIEW = 6;

	private ViewGroup editView;
	private Button btnConsumeType;
	private Button btnPayAcount;
	private Button btnPayTime;

	private EditText etPayItem;
	private EditText etPayAmount;
	private EditText etPayAddress;
	private EditText etConsumeDesc;
	private LayoutInflater mInflater;

	private AlertDialog datePickDialog;
	private Uri uri;
	// ----------fields for record the value -----------------
	private int mState;
	private Bundle bundle;

	// --------------- cache data -------------
	final ArrayList<String> consumeTypes = new ArrayList<String>();
	final ArrayList<String> incomeTypes = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		init(savedInstanceState);
		initCacheData();
	}

	private void init(Bundle savedInstanceState) {
		setContentView(R.layout.act_record);
		mInflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		bundle = null;
		Intent intent = getIntent();
		String action = intent.getAction();
		
		final boolean hasIncomingState = savedInstanceState != null
				&& savedInstanceState.containsKey("hasValue");
		if (ACTION_CONSUME_RECORD_ADD.equals(action)) {
			mState = ACTIVITY_STATUS_CONSUME_ADD;
			if (hasIncomingState) {
				bundle = savedInstanceState;
			}else if(intent.hasExtra("TEMPLATE_VALUES")){
				bundle = intent.getBundleExtra("TEMPLATE_VALUES");
			}
			setTitle(getString(R.string.str_acountRecorder));
		} else if (ACTION_CONSUME_RECORD_VIEW.equals(action)) {
			mState = ACTIVITY_STATUS_CONSUME_VIEW;
			uri = intent.getData();
			setTitle(getString(R.string.str_acountRecorder));
		} else if (ACTION_INCOME_RECORD_ADD.equals(action)) {
			mState = ACTIVITY_STATUS_INCOME_ADD;
			if (hasIncomingState) {
				bundle = savedInstanceState;
			}else if(intent.hasExtra("TEMPLATE_VALUES")){
				bundle = intent.getBundleExtra("TEMPLATE_VALUES");
			}
			setTitle(getString(R.string.str_incomerecoder));
		} else if (ACTION_INCOME_RECORD_VIEW.equals(action)) {
			mState = ACTIVITY_STATUS_INCOME_VIEW;
			uri = intent.getData();
			setTitle(getString(R.string.str_incomerecoder));
		}
	}

	private void initCacheData() {
		// init consume types data .
		initTypes(0,consumeTypes);
		// init income types data.
		initTypes(1,incomeTypes);
	}

	private void initTypes(int itype,ArrayList<String> list) {
		String locale = this.getResources().getConfiguration().locale.getLanguage();
		if (list.size() <= 0) {
			String selection = com.wifeacountbook.util.AcountKeeper.ConsumeType.TYPE
					+ " = " + itype +" and "+com.wifeacountbook.util.AcountKeeper.ConsumeType.LANG +" = '" +locale+"'";
			Cursor c = getContentResolver().query(
					AcountKeeper.ConsumeType.CONTENT_URI, null, selection,
					null, AcountKeeper.ConsumeType._ID + " ASC");
			if (c != null) {
				while (c.moveToNext()) {
					String type = c
							.getString(c
									.getColumnIndex(com.wifeacountbook.util.AcountKeeper.ConsumeType.TYPENAME));
					list.add(type);
				}
			}
			c.close();
		}
	}

	private String getDateString(Date d, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(d);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		getCurrentValuesAsBundle(outState);
	}

	@Override
	protected void onResume() {
		super.onResume();
		initView();
	}

	private void initView() {
		editView = (ViewGroup) findViewById(R.id.editors);
		Button btnAdd = (Button) findViewById(R.id.btn_done);
		if (mState == ACTIVITY_STATUS_CONSUME_ADD
				|| mState == ACTIVITY_STATUS_CONSUME_VIEW){
			if(mState == ACTIVITY_STATUS_CONSUME_VIEW){
				btnAdd.setText(getString(R.string.str_add_recorde));
			}
			this.getLayoutInflater().inflate(R.layout.record, editView, true);
		}else if (mState == ACTIVITY_STATUS_INCOME_ADD
				|| mState == ACTIVITY_STATUS_INCOME_VIEW){
			if(mState == ACTIVITY_STATUS_INCOME_VIEW){
				btnAdd.setText(getString(R.string.str_add_recorde));
			}
			this.getLayoutInflater().inflate(R.layout.income_record, editView,
					true);
		}
			

		if (mState == ACTIVITY_STATUS_CONSUME_ADD
				|| mState == ACTIVITY_STATUS_INCOME_ADD) {
			initAddView();
		} else if (mState == ACTIVITY_STATUS_CONSUME_VIEW
				|| mState == ACTIVITY_STATUS_INCOME_VIEW) {
			initViewerView();
		}
	}

	private void initViewerView() {
		if (uri != null) {
			Cursor c = getContentResolver().query(uri, null, null, null,
					null);
			if (c != null && c.moveToFirst()) {
				btnConsumeType = (Button) findViewById(R.id.btn_consume_type);
				btnPayAcount = (Button) findViewById(R.id.btn_consume_paytype);
				btnPayTime = (Button) findViewById(R.id.btn_consume_time);
				etPayItem = (EditText) findViewById(R.id.consume_item);
				etPayAmount = (EditText) findViewById(R.id.consume_money);
				etPayAddress = (EditText) findViewById(R.id.consume_address);
				etConsumeDesc = (EditText) findViewById(R.id.consume_desc);
				if (mState == ACTIVITY_STATUS_CONSUME_VIEW) {
					String etPayItemText = c.getString(c
							.getColumnIndex(ConsumeDetail.CONSUMEITEM));
					String etConsumeDescText = c.getString(c
							.getColumnIndex(ConsumeDetail.DESC));
					String etAddressText = c.getString(c
							.getColumnIndex(ConsumeDetail.ADDRESS));
					String consumeTime = c.getString(c
							.getColumnIndex(ConsumeDetail.CONSUMETIME));
					String consumeTypeText = c.getString(c
							.getColumnIndex(ConsumeDetail.PAYTYPE));
					String payAcountText = c.getString(c
							.getColumnIndex(ConsumeDetail.ACOUNTID));
					int money = c.getInt(c
							.getColumnIndex(ConsumeDetail.MONEY));

					btnConsumeType.setText(consumeTypeText);
					btnPayAcount.setText(payAcountText);
					btnPayTime.setText(consumeTime);
					etPayItem.setText(etPayItemText);
					etPayAmount.setText("" + money);
					etPayAddress.setText(etAddressText);
					etConsumeDesc.setText(etConsumeDescText);
				} else if (mState == ACTIVITY_STATUS_INCOME_VIEW) {
					String etPayItemText = c
							.getString(c
									.getColumnIndex(com.wifeacountbook.util.AcountKeeper.IncomeDetail.INCOMEITEM));
					String etConsumeDescText = c
							.getString(c
									.getColumnIndex(com.wifeacountbook.util.AcountKeeper.IncomeDetail.DESC));
					String etAddressText = c
							.getString(c
									.getColumnIndex(com.wifeacountbook.util.AcountKeeper.IncomeDetail.ADDRESS));
					String consumeTime = c
							.getString(c
									.getColumnIndex(com.wifeacountbook.util.AcountKeeper.IncomeDetail.INCOMETIME));
					String consumeTypeText = c
							.getString(c
									.getColumnIndex(com.wifeacountbook.util.AcountKeeper.IncomeDetail.PAYTYPE));
					String payAcountText = c
							.getString(c
									.getColumnIndex(com.wifeacountbook.util.AcountKeeper.IncomeDetail.ACOUNTID));
					int money = c
							.getInt(c
									.getColumnIndex(com.wifeacountbook.util.AcountKeeper.IncomeDetail.MONEY));

					btnConsumeType.setText(consumeTypeText);
					btnPayAcount.setText(payAcountText);
					btnPayTime.setText(consumeTime);
					etPayItem.setText(etPayItemText);
					etPayAmount.setText("" + money);
					etPayAddress.setText(etAddressText);
					etConsumeDesc.setText(etConsumeDescText);
				}

				etPayItem.setEnabled(false);
				etPayAmount.setEnabled(false);
				etPayAddress.setEnabled(false);
				etPayItem.setEnabled(false);
			}
		}
	}

	private void initAddView() {
		btnConsumeType = (Button) findViewById(R.id.btn_consume_type);
		btnPayAcount = (Button) findViewById(R.id.btn_consume_paytype);
		btnPayTime = (Button) findViewById(R.id.btn_consume_time);
		etPayItem = (EditText) findViewById(R.id.consume_item);
		etPayAmount = (EditText) findViewById(R.id.consume_money);
		etPayAddress = (EditText) findViewById(R.id.consume_address);
		etConsumeDesc = (EditText) findViewById(R.id.consume_desc);

		btnConsumeType.setOnClickListener(this);
		btnPayAcount.setOnClickListener(this);
		btnPayTime.setOnClickListener(this);

		// init the value.
		btnPayTime.setText(getDateString(new Date(), "yyyy-MM-dd"));
		if (mState == ACTIVITY_STATUS_CONSUME_ADD
				&& consumeTypes.size() > 0) {
			btnConsumeType.setText(consumeTypes.get(0));
		} else if (mState == ACTIVITY_STATUS_INCOME_ADD
				&& incomeTypes.size() > 0) {
			btnConsumeType.setText(incomeTypes.get(0));
		}

		if (bundle != null) {
			btnConsumeType.setText(bundle.getString("consumeTypeText"));
			int payAmount = bundle.getInt("payMoney");
			if(payAmount > 0 )
				etPayAmount.setText(""+payAmount);
			else 
				etPayAmount.setText("");
			
			btnPayAcount.setText(bundle.getString("payAcountText"));
			btnPayTime.setText(bundle.getString("consumeTime"));
			etPayItem.setText(bundle.getString("etPayItemText"));
			etPayAddress.setText(bundle.getString("etAddressText"));
			etConsumeDesc.setText(bundle.getString("etConsumeDescText"));
		}
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case CONSUME_TYPE_DIALOG_ID:
			final ArrayList<String> types = new ArrayList<String>();
			// create a type select dialog.
			if (mState == ACTIVITY_STATUS_CONSUME_ADD) {
				types.addAll(consumeTypes);
			} else if (mState == ACTIVITY_STATUS_INCOME_ADD) {
				types.addAll(incomeTypes);
			}

			final Context dialogContext = new ContextThemeWrapper(this,
					android.R.style.Theme_Light);
			final LayoutInflater dialogInflater = mInflater
					.cloneInContext(dialogContext);
			final ListAdapter listAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, types) {
				@Override
				public View getView(int position, View convertView,
						ViewGroup parent) {
					if (convertView == null) {
						convertView = (TextView) dialogInflater.inflate(
								android.R.layout.simple_list_item_1, parent,
								false);
					}
					TextView view = (TextView) convertView;
					view.setText(types.get(position));
					return view;
				}
			};

			final AlertDialog.Builder builder = new AlertDialog.Builder(this)
					.setTitle(R.string.consume_type).setAdapter(listAdapter,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									btnConsumeType.setText(types.get(which));
								}
							});
			return builder.create();
		case PAY_ACOUNT_DIALOG_ID:
			final ArrayList<String> Acounts = new ArrayList<String>();
			Acounts.add(getString(R.string.str_item_cash));
			Acounts.add(getString(R.string.str_item_bank_card));
			final Context dialogContext2 = new ContextThemeWrapper(this,
					android.R.style.Theme_Light);
			final LayoutInflater dialogInflater2 = mInflater
					.cloneInContext(dialogContext2);
			final ListAdapter listAdapter2 = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, Acounts) {
				@Override
				public View getView(int position, View convertView,
						ViewGroup parent) {
					if (convertView == null) {
						convertView = (TextView) dialogInflater2.inflate(
								android.R.layout.simple_list_item_1, parent,
								false);
					}
					TextView view = (TextView) convertView;
					view.setText(Acounts.get(position));
					return view;
				}
			};

			return new AlertDialog.Builder(this)
					.setTitle(R.string.consume_type).setAdapter(listAdapter2,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									btnPayAcount.setText(Acounts.get(which));
								}
							}).create();
		case PAY_TIME_DIALOG_ID:
			View date_pick = this.getLayoutInflater().inflate(
					R.layout.date_pick, editView, false);
			datePickDialog = new AlertDialog.Builder(this).setTitle(
					R.string.consume_time).setPositiveButton(
					R.string.str_check, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (datePickDialog != null) {
								DatePicker datepick = (DatePicker) datePickDialog
										.findViewById(R.id.datePicker1);
								int year = datepick.getYear();
								int month = datepick.getMonth();
								int day = datepick.getDayOfMonth();
								Calendar c = Calendar.getInstance();
								c.set(year, month, day);
								btnPayTime.setText(getDateString(c.getTime(),
										"yyyy-MM-dd"));
								datePickDialog.dismiss();
							}
						}
					}).setNegativeButton(R.string.str_chancel,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (datePickDialog != null)
								datePickDialog.cancel();
						}
					}).setView(date_pick).create();
			
			return datePickDialog;
		default:
			break;
		}
		return null;
	}

	@Override
	public void onClick(View v) {
		if (v == null)
			return;
		if (v.getId() == btnConsumeType.getId()) {
			showDialog(CONSUME_TYPE_DIALOG_ID);
		} else if (v.getId() == btnPayAcount.getId()) {
			showDialog(PAY_ACOUNT_DIALOG_ID);
		} else if (v.getId() == btnPayTime.getId()) {
			showDialog(PAY_TIME_DIALOG_ID);
		} else if (v.getId() == R.id.btn_done) {
			if (mState == ACTIVITY_STATUS_CONSUME_VIEW) {
				Intent intent = new Intent(AcountRecorder.ACTION_CONSUME_RECORD_ADD);
				Bundle outState = new Bundle();
				getCurrentValuesAsBundle(outState);
				outState.putInt("payMoney", 0);
				intent.putExtra("TEMPLATE_VALUES", outState);
				intent.setClass(this, AcountRecorder.class);
				startActivity(intent);
				
				finish();
			} else if(mState == ACTIVITY_STATUS_INCOME_VIEW){
				Intent intent = new Intent(AcountRecorder.ACTION_INCOME_RECORD_ADD);
				Bundle outState = new Bundle();
				getCurrentValuesAsBundle(outState);
				outState.putInt("payMoney", 0);
				intent.putExtra("TEMPLATE_VALUES", outState);
				intent.setClass(this, AcountRecorder.class);
				startActivity(intent);
				
				finish();
			}
			else {
				saveRecord();
				finish();
			}
		} else if (v.getId() == R.id.btn_chancel) {
			finish();
		} else {

		}
	}

	private void getCurrentValuesAsBundle(Bundle outState) {
		int payMoney = 0;
		String payAmountTxt = etPayAmount.getText().toString();
		if (TextUtils.isDigitsOnly(payAmountTxt)) {
			payMoney = Integer.parseInt(payAmountTxt);
		}

		String etPayItemText = etPayItem.getText().toString();
		String etConsumeDescText = etConsumeDesc.getText().toString();
		String etAddressText = etPayAddress.getText().toString();
		String consumeTime = btnPayTime.getText().toString();
		String consumeTypeText = btnConsumeType.getText().toString();
		String payAcountText = btnPayAcount.getText().toString();

		outState.putInt("payMoney", payMoney);
		outState.putString("etPayItemText", etPayItemText);
		outState.putString("etConsumeDescText", etConsumeDescText);
		outState.putString("etAddressText", etAddressText);
		outState.putString("consumeTime", consumeTime);
		outState.putString("consumeTypeText", consumeTypeText);
		outState.putString("payAcountText", payAcountText);
	}

	private boolean saveRecord() {
		int payMoney = 0;
		String payAmount = etPayAmount.getText().toString();
		if (!TextUtils.isEmpty(payAmount) && TextUtils.isDigitsOnly(payAmount)) {
			payMoney = Integer.parseInt(payAmount);
		}

		if (payMoney <= 0) {
			Toast.makeText(this, R.string.str_error_savefail, 1000).show();
			return false;
		}

		String etPayItemText = etPayItem.getText().toString();
		String etConsumeDescText = etConsumeDesc.getText().toString();
		String etAddressText = etPayAddress.getText().toString();
		String consumeTime = btnPayTime.getText().toString();
		String consumeTypeText = btnConsumeType.getText().toString();
		String payAcountText = btnPayAcount.getText().toString();

		ContentValues values = new ContentValues();
		Uri result = null;
		if (mState == ACTIVITY_STATUS_CONSUME_ADD) {
			values.put(ConsumeDetail.ADDRESS, etAddressText);
			values.put(ConsumeDetail.DESC, etConsumeDescText);
			values.put(ConsumeDetail.PAYTYPE, consumeTypeText);
			values.put(ConsumeDetail.MONEY, payMoney);
			values.put(ConsumeDetail.CONSUMEITEM, etPayItemText);
			values.put(ConsumeDetail.CONSUMETIME, consumeTime);
			values.put(ConsumeDetail.ACOUNTID, payAcountText);

			result = getContentResolver().insert(ConsumeDetail.CONTENT_URI,
					values);
		} else if (mState == ACTIVITY_STATUS_INCOME_ADD) {
			values.put(IncomeDetail.ADDRESS, etAddressText);
			values.put(IncomeDetail.DESC, etConsumeDescText);
			values.put(IncomeDetail.PAYTYPE, consumeTypeText);
			values.put(IncomeDetail.MONEY, payMoney);
			values.put(IncomeDetail.INCOMEITEM, etPayItemText);
			values.put(IncomeDetail.INCOMETIME, consumeTime);
			values.put(IncomeDetail.ACOUNTID, payAcountText);

			result = getContentResolver().insert(IncomeDetail.CONTENT_URI,
					values);
		}

		if (result != null) {
			Toast.makeText(this, R.string.str_error_savesuc, 1000).show();
			return true;
		} else {
			Toast.makeText(this, R.string.str_error_savefail, 1000).show();
			return false;
		}

	}
}
